<?php 
class Store_Model_City {
	
	private static $_session_namespace = 'Store_City';
	
	public static function setCity($alias = null) {
		if ( $alias ) {
			$city_item = self::getCityByAlias($alias);
			self::_setCityToSession($city_item);
		} else {
			$city_item = self::_getCityFromSession();
			if (! $city_item) {
				$city_item = self::_setCityByIp();
			}
		}
		return $city_item;
	}
	
	public static function getCity() {
		return self::setCity();
	}
	
	private static function _setCityByIp() {
		$ip = Zen_User::getip ();
		$validator = new Zend_Validate_Ip ();
		$alias = null;
		if ($validator->isValid ( $ip )) {
			$geo = new Store_Model_Geo ();
 
			$data = $geo->getInfo ( $ip);
			
			if (isset ( $data ['lat'] ) && isset ( $data ['lng'] )) {
				$lat = $data ['lat'];
				$lng = $data ['lng'];
				$table = new Zend_Db_Table('store_city');
				$expression = "min(SQRT(POW(ABS(dolgota-" . $lat . "),2)+POW(ABS(shirota-" . $lng . "),2)))  as `length`";
				$data = $table->select ()->from ( ($table), array ('alias', new Zend_Db_Expr ( $expression ) ) )->group ( 'alias' )->order ( 'length' )->limit ( 1 )->query ()->fetchAll ();
				if (isset ( $data [0] ['alias'] )) {
					$alias = $data [0] ['alias'];
				}
			}
		}
		$city_item = self::getCityByAlias($alias);
		self::_setCityToSession($city_item);
		return $city_item;
	}
	
	private static function _setCityToSession($city_item) {
		$session = self::_getSessionStorage();
		$session->storage = $city_item;
	}

	private static function _getCityFromSession() {
		$session = self::_getSessionStorage();
		$city_item = $session->storage; 
		return $city_item;
	} 
	
	private static function _getSessionStorage() {
		$session = new Zend_Session_Namespace ( 'Store_City' );
		$session->setExpirationSeconds(600);
		return $session;
	}
	
	public static function getCityByAlias($alias) {
		$model = new Store_Model_Tree();
		if ($alias) {
			$res = $model->getCityByAlias($alias);
		} else {
			$res = $model->getCityList();
			$res = ($res) ? $res[0] : false;
		} 
			
		return $res;
	}
	
}